home *** CD-ROM | disk | FTP | other *** search
- Path: rcp6.elan.af.mil!rscernix!danpop
- From: danpop@mail.cern.ch (Dan Pop)
- Newsgroups: comp.lang.c
- Subject: Re: simple code, argc, argv, strcmp()
- Date: 16 Feb 96 14:39:15 GMT
- Organization: CERN European Lab for Particle Physics
- Message-ID: <danpop.824481555@rscernix>
- References: <11f7cc$17261a.3b3@daprez> <9602011151.AA04526@dxmint.cern.ch> <4g040v$7jj@maverick.tad.eds.com>
- NNTP-Posting-Host: ues5.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
-
- In <4g040v$7jj@maverick.tad.eds.com> gulleha@vaxixhp3.vaxix.slg.eds.com (Harold Guller) writes:
-
- >In article <9602011151.AA04526@dxmint.cern.ch>, danpop@mail.cern.ch (Dan Pop) says:
- >>>int main (int argc, char **argv) {
- >>>
- >>> if (!strcmp(argv[1],"-d") || !strcmp(argv[1],"-e")) {
- >>> Usage();
- >>> }
- >>...
- >>>
- >>>Can someone see what's wrong with this ?
- >>>am I not using strcmp() right ?
- >>
- >>Right :-)
- >>
- >>Your code is equivalent to:
- >>
- >> if (strcmp(argv[1],"-d") == 0 || strcmp(argv[1],"-e") == 0) Usage();
- >>
- >>Which means that any time the program is correctly invoked, it will call
- >>Usage!
- >>
- >>So:
- >>
- >>1. Never use ! with strcmp. It's a good way to shoot yourself in the foot.
- >
- >You can say that about anything that someone does not understad.
- >A better solution is to learn the concept. The "!" operator is widely
- >used and should be understood.
-
- Can't you read (and understand) a (fairly short) statement? I didn't
- advocate against the usage of the ! operator, I did advocate against
- !strcmp(). This _is_ confusing even for people who understand both
- the ! operator and the strcmp function and can lead to errors unless
- the programmer is extremely careful. Even if s/he is, the big point is
- that _conceptually_, it makes no sense to apply the ! operator to a
- function which doesn't return a "logical" value, even if the language
- allows this and the resulting code works fine.
-
- >>3. Are you sure you didn't mean && when you wrote ||? Even if !strcmp()
- >> would have worked as you thought it did, the || operator would have
- >> caused the expression inside the if statement to _always_ evaluate to 1.
- >
- >Why do you advise learning the "&&" and "||" conditions? These are more
- >complex than the "!" operator, and he did "shoot himself in the foot".
- >Shoudn't he use nested if else contrcuts to achieve his purpose?
-
- Nested if-else constructs lead to more complex code which makes shooting
- yourself in the foot even easier. All C operators should be understood
- and used _properly_. The usage of ! in this example is a mistake, the
- usage of the && operator is the right thing.
-
- BTW, K&R2 introduces the && and || operators at page 21. Way before the
- ! operator (page 41) or strcmp (page 106).
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-